<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>$Title$</title>
    <script type="text/javascript" src="./jquery.min.js"></script>
    <style>
        body {
            background: rgb(46, 46, 50);
            color: white;
            font-family: consolas;
        }

        pre {
            font-family: 'consolas';
        }

        .Canvas {
            font: 14px/18px 'consolas';
            background-color: #ECECEC;
            color: #000000;
            border: solid 1px #CECECE;
        }

        .ObjectBrace {
            color: #00AA00;
            font-weight: bold;
        }

        .ArrayBrace {
            color: #0033FF;
            font-weight: bold;
        }

        .PropertyName {
            color: #CC0000;
            font-weight: bold;
        }

        .String {
            color: #007777;
        }

        .Number {
            color: #AA00AA;
        }

        .Boolean {
            color: #0000FF;
        }

        .Function {
            color: #AA6633;
            text-decoration: italic;
        }

        .Null {
            color: #0000FF;
        }

        .Comma {
            color: #000000;
            font-weight: bold;
        }

        PRE.CodeContainer {
            margin-top: 0px;
            margin-bottom: 0px;
        }
    </style>
</head>
<body>
<div>
    <div style="display: flex; align-content: space-between;padding-top: 5px">
        <select id="method"
                style="padding: 0 5px;margin-right: 5px;box-shadow: 0px 0px 5px 5px rgb(38 39 41);border: none;border-radius: 5px;width: 10%;background: rgb(53,53,59);color: white">
            <option>GET</option>
            <option>POST</option>
        </select>
        <input id="url" placeholder="请输入请求的路径"
               style="color: white;padding: 7px;border: none;font-size: 14px;flex: 3; background: rgb(37,37,41); "/>
        <button id="submit"
                style="cursor:pointer;border: none;border-radius: 5px;color: white;margin-left: 15px;width: 10%; background: rgb(78,132,246); padding: 5px">
            发送
        </button>
    </div>
    <div style="display: flex;justify-content: space-between;margin-top: 20px">

        <div style="flex: 1">
            <span>Header</span>
            <div id="headers-box" style="margin-top: 10px;position: relative">
                <div class="headers" style="display: flex">
                    <div>
                        <div style="border: 1px solid rgb(56,57,59);padding: 5px;font-size: 12px">参数名：</div>
                        <input class="key" placeholder="参数名"
                               style="width: 150px;padding: 5px;color: white;font-size: 12px;border: 1px solid rgb(56,57,59);border-top: none;background: rgb(45,46,50);"/>
                    </div>
                    <div style="margin-left: 10px">
                        <div style="border: 1px solid rgb(56,57,59);padding: 5px;font-size: 12px">参数值：</div>
                        <input class="value" placeholder="参数值"
                               style="width:150px;padding: 5px;color: white;font-size: 12px;border: 1px solid rgb(56,57,59);border-top: none;background: rgb(45,46,50);"/>
                    </div>
                </div>
                <button id="add-headers"
                        style="cursor:pointer;position: absolute;top: -35px;right: 85px;font-size: 12px;display: inline-block;border: none;border-radius: 5px;margin-left: 15px;color: white;background: rgb(78,131,247);padding: 3px 10px;height: 30px">
                    添加参数
                </button>
            </div>
        </div>

        <div style="flex: 1">
            <span>Query</span>
            <div id="params-box" style="margin-top: 10px;position: relative">
                <div class="params" style="display: flex">
                    <div>
                        <div style="border: 1px solid rgb(56,57,59);padding: 5px;font-size: 12px">参数名：</div>
                        <input class="key" placeholder="参数名"
                               style="width: 150px;padding: 5px;color: white;font-size: 12px;border: 1px solid rgb(56,57,59);border-top: none;background: rgb(45,46,50);"/>
                    </div>
                    <div style="margin-left: 10px">
                        <div style="border: 1px solid rgb(56,57,59);padding: 5px;font-size: 12px">参数值：</div>
                        <input class="value" placeholder="参数值"
                               style="width:150px;padding: 5px;color: white;font-size: 12px;border: 1px solid rgb(56,57,59);border-top: none;background: rgb(45,46,50);"/>
                    </div>
                </div>
                <button id="add-params"
                        style="cursor:pointer;position: absolute;top: -35px;right: 85px;font-size: 12px;display: inline-block;border: none;border-radius: 5px;margin-left: 15px;color: white;background: rgb(78,131,247);padding: 3px 10px;height: 30px">
                    添加参数
                </button>
            </div>
        </div>

        <div style="flex: 1">
            <span>Body</span>
            <div id="body-box" style="margin-top: 10px;position: relative">
                <textarea id="request-body" placeholder="请求体" onchange="changeHandle()"
                          style="height: 200px;width: 100%;padding: 5px;color: white;font-size: 14px;border: 1px solid rgb(56,57,59);background: rgb(45,46,50);"></textarea>
            </div>
        </div>
    </div>

</div>
<div style="margin-top: 40px">
    <div style="border-bottom: 2px solid rgb(225,115,73);width: 7%;text-align: center;">响应结果</div>
    <p id="responseBody" style="height: 300px;width: 100%;border: 1px solid rgb(56,57,59)">

    </p>
</div>
</body>

<script>

    $("#submit").click(function () {
        $.ajax(
            {
                url: "http://localhost:8080/send-request",
                type: "post",
                data: getParams(),
                success: function (res) {
                    console.log("success")
                    console.log(res)
                    var resultJson = formatJson(JSON.stringify(res));
                    //(3)将格式化好后的json写入页面中
                    document.getElementById("responseBody").innerHTML = '<pre>' +resultJson + '<pre/>';
                },
                error: function (res) {
                    console.log("error")
                    console.log(res)
                }
            }
        )

    })

    $("#add-params").click(function () {
        $("#params-box").append(
            '<div class="params" style="display: flex"><div><div style="border: 1px solid rgb(56,57,59);padding: 5px;font-size: 12px;display: none">参数名：</div> <input class="key" placeholder="参数值" style="width: 150px;padding: 5px;color: white;font-size: 12px;border: 1px solid rgb(56,57,59);border-top: none;background: rgb(45,46,50);"/> </div><div style="margin-left: 10px"><div style="border: 1px solid rgb(56,57,59);padding: 5px;font-size: 12px;display: none">参数值：</div> <input class="value" placeholder="参数值" style="width:150px;padding: 5px;color: white;font-size: 12px;border: 1px solid rgb(56,57,59);border-top: none;background: rgb(45,46,50);"/> </div></div></div>'
        )
    })

    $("#add-headers").click(function () {
        $("#headers-box").append(
            '<div class="headers" style="display: flex"><div><div style="border: 1px solid rgb(56,57,59);padding: 5px;font-size: 12px;display: none">参数名：</div> <input class="key" placeholder="参数值" style="width: 150px;padding: 5px;color: white;font-size: 12px;border: 1px solid rgb(56,57,59);border-top: none;background: rgb(45,46,50);"/> </div><div style="margin-left: 10px"><div style="border: 1px solid rgb(56,57,59);padding: 5px;font-size: 12px;display: none">参数值：</div> <input class="value" placeholder="参数值" style="width:150px;padding: 5px;color: white;font-size: 12px;border: 1px solid rgb(56,57,59);border-top: none;background: rgb(45,46,50);"/> </div></div></div>'
        )
    })

    function changeHandle(){
        let text = $("#request-body").val()
        var resultJson = formatJson(JSON.stringify(text));
        //(3)将格式化好后的json写入页面中
        //$("#request-body").val(resultJson) ;
    }

    function getParams() {
        let url = $("#url").val()
        if (!url) {
            alert("请输入请求地址")
            return
        }
        let method = $("#method").val()
        let requestBody = $("#request-body").val()
        let params = $("#params-box .params")

        let paramsStr = ''
        for (let i = 0; i < params.length; i++) {
            paramsStr +=  $($(params[i]).children("div").get(0)).children(".key").val()
            paramsStr += '='
            paramsStr += $($(params[i]).children("div").get(1)).children(".value").val()
            paramsStr += '&'
        }
        paramsStr = paramsStr.substring(0, paramsStr.length - 1)

        let headersStr = ''
        let headers = $("#headers-box .headers")
        for (let i = 0; i < headers.length; i++) {
            headersStr += $($(headers[i]).children("div").get(0)).children(".key").val()
            headersStr += '='
            headersStr += $($(headers[i]).children("div").get(1)).children(".value").val()
            headersStr += '&'
        }
        headersStr = headersStr.substring(0, headersStr.length - 1)

        return {
            'url': url,
            'method': method,
            'headers': headersStr,
            'params': paramsStr,
            'body': requestBody
        }
    }

    Process();
    function formatJson(json, options) {
        var reg = null,
            formatted = '',
            pad = 0,
            PADDING = '    ';
        options = options || {};
        options.newlineAfterColonIfBeforeBraceOrBracket = (options.newlineAfterColonIfBeforeBraceOrBracket === true) ? true : false;
        options.spaceAfterColon = (options.spaceAfterColon === false) ? false : true;
        if (typeof json !== 'string') {
            json = JSON.stringify(json);
        } else {
            json = JSON.parse(json);
            json = JSON.stringify(json);
        }
        reg = /([\{\}])/g;
        json = json.replace(reg, '\r\n$1\r\n');
        reg = /([\[\]])/g;
        json = json.replace(reg, '\r\n$1\r\n');
        reg = /(\,)/g;
        json = json.replace(reg, '$1\r\n');
        reg = /(\r\n\r\n)/g;
        json = json.replace(reg, '\r\n');
        reg = /\r\n\,/g;
        json = json.replace(reg, ',');
        if (!options.newlineAfterColonIfBeforeBraceOrBracket) {
            reg = /\:\r\n\{/g;
            json = json.replace(reg, ':{');
            reg = /\:\r\n\[/g;
            json = json.replace(reg, ':[');
        }
        if (options.spaceAfterColon) {
            reg = /\:/g;
            json = json.replace(reg, ':');
        }
        (json.split('\r\n')).forEach(function (node, index) {
            //console.log(node);
            var i = 0,
                indent = 0,
                padding = '';

            if (node.match(/\{$/) || node.match(/\[$/)) {
                indent = 1;
            } else if (node.match(/\}/) || node.match(/\]/)) {
                if (pad !== 0) {
                    pad -= 1;
                }
            } else {
                indent = 0;
            }

            for (i = 0; i < pad; i++) {
                padding += PADDING;
            }

            formatted += padding + node + '\r\n';
            pad += indent;
        });
        return formatted;
    };

    //着色
    function IsArray(obj) {
        return obj &&
            typeof obj === 'object' &&  typeof obj.length === 'number' && !(obj.propertyIsEnumerable('length'));
    }
    function Process() {
        var json = $('#show').text();
        var html = "";
        try {
            if (json == "") {
                json = '""';
            }
            var obj = eval("[" + json + "]");
            html = ProcessObject(obj[0], 0, false, false, false);
            $("#show").html(html);
        } catch(e) {
        }
    }
    function ProcessObject(obj, indent, addComma, isArray, isPropertyContent) {
        var html = "";
        var comma = (addComma) ? "<span class='Comma'>,</span> ": "";
        var type = typeof obj;
        if (IsArray(obj)) {
            if (obj.length == 0) {
                html += GetRow(indent, "<span class='ArrayBrace'>[ ]</span>" + comma, isPropertyContent);
            } else {
                html += GetRow(indent, "<span class='ArrayBrace'>[</span>", isPropertyContent);
                for (var i = 0; i < obj.length; i++) {
                    html += ProcessObject(obj[i], indent + 1, i < (obj.length - 1), true, false);
                }
                html += GetRow(indent, "<span class='ArrayBrace'>]</span>" + comma);
            }
        } else {
            if (type == "object" && obj == null) {
                html += FormatLiteral("null", "", comma, indent, isArray, "Null");
            } else {
                if (type == "object") {
                    var numProps = 0;
                    for (var prop in obj) {
                        numProps++;
                    }
                    if (numProps == 0) {
                        html += GetRow(indent, "<span class='ObjectBrace'>{ }</span>" + comma, isPropertyContent)
                    } else {
                        html += GetRow(indent, "<span class='ObjectBrace'>{</span>", isPropertyContent);
                        var j = 0;
                        for (var prop in obj) {
                            html += GetRow(indent + 1, '<span class="PropertyName">"' + prop + '"</span>: ' + ProcessObject(obj[prop], indent + 1, ++j < numProps, false, true))
                        }
                        html += GetRow(indent, "<span class='ObjectBrace'>}</span>" + comma);
                    }
                } else {
                    if (type == "number") {
                        html += FormatLiteral(obj, "", comma, indent, isArray, "Number");
                    } else {
                        if (type == "boolean") {
                            html += FormatLiteral(obj, "", comma, indent, isArray, "Boolean");
                        } else {
                            if (type == "function") {
                                obj = FormatFunction(indent, obj);
                                html += FormatLiteral(obj, "", comma, indent, isArray, "Function");
                            } else {
                                if (type == "undefined") {
                                    html += FormatLiteral("undefined", "", comma, indent, isArray, "Null");
                                } else {
                                    html += FormatLiteral(obj, '"', comma, indent, isArray, "String");
                                }
                            }
                        }
                    }
                }
            }
        }
        return html;
    };

    function FormatLiteral(literal, quote, comma, indent, isArray, style) {
        if (typeof literal == "string") {
            literal = literal.split("<").join("&lt;").split(">").join("&gt;");
        }
        var str = "<span class='" + style + "'>" + quote + literal + quote + comma + "</span>";
        if (isArray) {
            str = GetRow(indent, str);
        }
        return str;
    }
    function FormatFunction(indent, obj) {
        var tabs = "";
        for (var i = 0; i < indent; i++) {
            tabs += "    ";
        }
        var funcStrArray = obj.toString().split("\n");
        var str = "";
        for (var i = 0; i < funcStrArray.length; i++) {
            str += ((i == 0) ? "": tabs) + funcStrArray[i] + "\n";
        }
        return str;
    }
    function GetRow(indent, data, isPropertyContent) {
        var tabs = "";
        for (var i = 0; i < indent && !isPropertyContent; i++) {
            tabs += "    ";
        }
        if (data != null && data.length > 0 && data.charAt(data.length - 1) != "\n") {
            data = data + "\n";
        }
        return tabs + data;
    };
</script>
</html>
